package cn.kk.communication.controller;
/*
 *@author KK on 2022.11.19 10:56
 */

import cn.kk.communication.entity.Communication;
import cn.kk.communication.service.CommunicationService;
import cn.kk.communication.service.impl.CommunicationServiceImpl;
import com.alibaba.druid.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    CommunicationService communicationService = new CommunicationServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String inputCode = request.getParameter("verificationCode");
        String sysCode = (String) request.getSession().getAttribute("code");
        String msg;
        if (inputCode.equalsIgnoreCase(sysCode)) {
            try {
                Communication communication = communicationService.getByName(username);
                if (communication != null) {
                    if (communication.getName().equals(username) && communication.getPassword().equals(password)) {
                        request.setAttribute("communication", communication);
                        request.getRequestDispatcher("index.jsp").forward(request, response);
                    } else {
                        msg = "用户名或者密码错误！";
                        request.setAttribute("msg", msg);
                        request.getRequestDispatcher("login.jsp").forward(request, response);
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            msg = "验证码输入有误";
            request.setAttribute("msg", msg);
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}
